# -*- coding: utf-8 -*-

from psychopy.visual import Window
from psychopy.core import Clock, quit
from psychopy.visual import TextStim
# from psychopy.visual import ImageStim
from psychopy.visual import Circle
from psychopy.visual import ShapeStim
import pylsl
from psychopy import core

from psychopy import event
import random
import json
from psychopy import sound
import os

task_name= 'psycho_marker_001' # find this task in lsl to get the marker

# same with BCIC IV 2a
trial_num = 48 # not guarantee, actually probably not, that 12 trials for each class
# trial_num = 36

imagine_duration = 2.75 
rest_duration = 2
cue_duration = 1.25
WAIT_ON_CROSS = 2

# imagine_duration = 0.275 
# rest_duration = 0.2
# cue_duration = 0.125
# WAIT_ON_CROSS = 0.2

task_json_file = os.path.join(os.path.dirname(__file__), "task_markers.json")

# with open('task_markers.json', 'r') as file:
with open(task_json_file, 'r') as file:
    markers = json.load(file)

def m_wait(t):
    cl = Clock()
    while cl.getTime() < t:
        keys = event.getKeys()
        # if len(keys)>0:
        #     print(keys)
        if 'escape' in keys:
            win.close()
            quit()
        core.wait(0.01)


def run_stim():
    global win
##############

    id_num = random.randint(1, 10000)
    task_source_id = 'psycho_marker_'+str(id_num)
    info = pylsl.stream_info(name = task_name, type='Markers', channel_count=1,
                      channel_format='int32', source_id=task_source_id)
    outlet = pylsl.stream_outlet(info)  

############################

    win = Window(size=(560, 480), fullscr=False)
    # win = Window(fullscr=True)

    instruction_text = TextStim(win,'''Imagine movements according to the signs ...
                                                
 left hand : ← 
 right hand : →  
 both foots : ↑
 relax : ↓

Press any key to begin''')
    instruction_text.draw()

    win.flip()

    # outlet.push_sample(markers['test'])

    event.waitKeys()

    # outlet.push_sample(markers['begin'])

    center_text = TextStim(win,'+')
    center_text.size=0.3

    stim_circle = Circle(win,radius=80,edges=128,units='pix',
        fillColor=[0.4375,0.5,0.5625])
    # stim_circle.draw()

    p1 = (-200, 0)
    p2 = (-100, 50)
    p3 = (-120,0)
    p4 = (-100, -50)

    left_tri = ShapeStim(win, fillColor='none',  
                             vertices=[p1, p2, p3, p4], lineColor='black',units='pix',
                             opacity=0.5)
    # left_tri.draw()


    p5 = (200, 0)
    p6 = (100, 50)
    p7 = (120,0)
    p8 = (100, -50)

    right_tri = ShapeStim(win, fillColor='none',
                             vertices=[p5, p6, p7, p8], lineColor='black',units='pix',
                             opacity=0.5)
    # right_tri.draw()

    p9 = (-50, 100)
    p10 = (0, 200)
    p11 = (50,100)
    p12 = (0, 120)
    up_tri = ShapeStim(win, fillColor='none',
                             vertices=[p9,p10,p11,p12], lineColor='black',units='pix',
                             opacity=0.5)
    # up_tri.draw()

    p13 = (-50, -100)
    p14 = (0, -200)
    p15 = (50,-100)
    p16 = (0, -120)
    down_tri = ShapeStim(win, fillColor='none',
                             vertices=[p13,p14,p15,p16], lineColor='black',units='pix',
                             opacity=0.5)
    # down_tri.draw()

    face_color_tri = [0.4627,0.9333,0.7765]
    m_sound = sound.Sound('A')

    def draw_all():
        left_tri.draw()
        right_tri.draw()
        up_tri.draw()
        down_tri.draw()
        stim_circle.draw()

    center_text.setText('3')
    center_text.draw()
    win.flip()
    m_wait(1)
    center_text.setText('2')
    center_text.draw()
    win.flip()
    m_wait(1)
    center_text.setText('1')
    center_text.draw()
    win.flip()
    m_wait(1)
    outlet.push_sample(markers['begin'])

    for i in range(trial_num):
        # 

        m_sound = sound.Sound('B')
        m_sound.play()

        print("remain trials: "+str(trial_num - i))
        draw_all()
        center_text.setText('+')
        center_text.draw()
        win.flip()
        m_wait(WAIT_ON_CROSS)
        
        rn = random.randint(1, 1000)
        # rn = i
        r_time = random.random()

        cl = rn % 4

        if cl == 3:
            down_tri.fillColor=face_color_tri
            draw_all()
            win.flip()
            outlet.push_sample(markers['Cue_onset_down'])
        elif cl == 2:
            up_tri.fillColor=face_color_tri
            draw_all()
            win.flip()
            outlet.push_sample(markers['Cue_onset_up'])
        elif cl == 1:
            right_tri.fillColor=face_color_tri
            draw_all()
            win.flip()
            outlet.push_sample(markers['Cue_onset_right'])
        elif cl == 0:
            left_tri.fillColor=face_color_tri
            draw_all()
            win.flip()
            outlet.push_sample(markers['Cue_onset_left'])

        m_wait(cue_duration)            
        left_tri.fillColor='none'
        right_tri.fillColor='none'
        up_tri.fillColor='none'
        down_tri.fillColor='none'
        draw_all()
        win.flip()

        m_wait(imagine_duration)            

        center_text.setText('rest')
        center_text.draw()
        win.flip()

        # outlet.push_sample(markers['trial_end'])

        m_wait(WAIT_ON_CROSS+r_time)

    ### END BODY OF EXPERIMENT ###

    # Finish experiment by closing window and quitting
    outlet.push_sample(markers['stop'])

    win.close()
    quit()

if __name__ == '__main__':
    # test1.py executed as script
    # do something
    run_stim()


